package com.lin.mr.maizilaundry.fragmentcloth;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.myadapter.ContactsAdapter;
import com.lin.mr.maizilaundry.myapplication.MyApplication;
import com.lin.mr.maizilaundry.utils.ContactsJean;
import com.lin.mr.maizilaundry.utils.ShareUtils;
import com.lin.mr.maizilaundry.utils.VolleyUtils;

/**
 * Created by lenovog on 2016/8/7.
 */
public class FragmentContacts extends Fragment {
    private ListView lv_contacts;
    private final String URL="http://cloud.bmob.cn/d9f6840be6bb07cf/friends_test?clive=contacts";
    private ContactsJean contactsInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contacts,container,false);
        lv_contacts = (ListView) view.findViewById(R.id.lv_contacts);

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            VolleyUtils.requestByGet(URL, "FragmentContacts", new VolleyUtils.CallBack() {
                @Override
                public void returnData(Object result) {
                    ShareUtils.putContactInfo(MyApplication.getContext(), (String) result);
                    if (result==null){
                        Toast.makeText(getActivity(), "请检查网络!", Toast.LENGTH_SHORT).show();
                    }else {
                        Gson gson = new Gson();
                        String cache = ShareUtils.getContactsInfo(MyApplication.getContext());
                        if (cache != null){
                            contactsInfo = gson.fromJson(cache,ContactsJean.class);
                        }else {
                            contactsInfo = gson.fromJson((String) result,ContactsJean.class);
                        }

                        lv_contacts.setAdapter(new ContactsAdapter(getActivity(),contactsInfo.getUserInfo()));
                    }
                }
            });
        }
    }
}
